import { StudyMatchResult } from '@/entity/study-match-result.entity';
import { User } from '@/entity/user.entity';
import { PageParamDto } from './dto/page-param.dto';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { BaseResponse } from '@/common/BaseResponse';

@Injectable()
export class MatchService {
  constructor(
    @InjectRepository(StudyMatchResult)
    private readonly studyMatchResultRepository: Repository<StudyMatchResult>,

    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

  async matchListSelect(pageParamDto: PageParamDto) {
    const qb =
      this.studyMatchResultRepository.createQueryBuilder('studyMatchResult');
    const result = qb;

    result
      .leftJoinAndMapOne(
        'studyMatchResult.matchOneUserInfo',
        User,
        'users',
        'users.id = studyMatchResult.matchOne',
      )
      .leftJoinAndMapOne(
        'studyMatchResult.matchTwoUserInfo',
        User,
        'user2',
        'user2.id = studyMatchResult.matchTwo',
      )
      .limit(pageParamDto.size)
      .offset((pageParamDto.page - 1) * pageParamDto.size);
    const total = await result.getCount();
    const list = await result.getMany();

    return BaseResponse.toSuccesJustData({
      page: Number(pageParamDto.page),
      list,
      size: Number(pageParamDto.size),
      total,
    });
  }

  deleteMatch(id: number) {
    return this.studyMatchResultRepository.delete(id);
  }
}
